package com.up.upzl.biz.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.up.upzl.base.service.impl.BaseServiceImpl;
import com.up.upzl.biz.domain.SysAccount;
import com.up.upzl.biz.domain.SysApp;
import com.up.upzl.biz.repository.SysAccountRepository;
import com.up.upzl.biz.service.SysAccountService;

@Service
public class SysAccountServiceImpl extends BaseServiceImpl<SysAccount, Long> implements SysAccountService {

	@Autowired
	private SysAccountRepository sysAccountRepository;

	@Override
	public Page<SysAccount> findByCondition(String name, String account, Pageable page) {
		return sysAccountRepository.findAll(new Specification<SysAccount>() {

			@Override
			public Predicate toPredicate(Root<SysAccount> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicates = new ArrayList<>();
				if (!StringUtils.isEmpty(name)) {
					predicates.add(cb.and(cb.like(cb.lower(root.get("name")), "%" + name.toLowerCase() + "%")));
				}
				if (!StringUtils.isEmpty(account)) {
					predicates.add(cb.and(cb.like(cb.lower(root.get("account")), "%" + account.toLowerCase() + "%")));
				}
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		}, page);
	}

	@Override
	public SysAccount findByAccountAndPassword(String account, String password) {
		return sysAccountRepository.findByAccountAndPassword(account, password);
	}

	@Override
	public SysAccount findAccountByAccount(String account) {
		// TODO 自动生成的方法存根
		return sysAccountRepository.findAccountByAccount(account);
	}

	@Override
	public List<SysApp> getSysAppsByUserId(Long id) {
		return sysAccountRepository.getSysAppsByUserId(id);
	}

	@Override
	public List<SysAccount> findAccountByRoleName(String name) {
		return sysAccountRepository.findAccountBySysRoleRoleName(name);
	}
}
